<template>
  <div class="container">
    <h1 class="page-title">车辆使用分析</h1>
    
    <div class="search-container">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :shortcuts="dateShortcuts"
        value-format="YYYY-MM-DD"
        @change="handleDateChange"
      />
      <el-select v-model="selectedVehicle" placeholder="选择车辆" clearable @change="loadData">
        <el-option
          v-for="vehicle in vehicles"
          :key="vehicle.id"
          :label="vehicle.vehicleNo"
          :value="vehicle.id"
        />
      </el-select>
      <el-button type="primary" @click="loadData">查询</el-button>
      <div class="flex-grow"></div>
      <el-button type="success" @click="exportToExcel">
        <el-icon class="mr-1"><Document /></el-icon>导出报表
      </el-button>
    </div>
    
    <div class="chart-grid">
      <el-card shadow="hover" class="chart-card">
        <template #header>
          <div class="flex justify-between items-center">
            <span>车辆使用频率（天）</span>
            <el-radio-group v-model="usageFreqType" size="small" @change="loadData">
              <el-radio-button label="month">月度</el-radio-button>
              <el-radio-button label="quarter">季度</el-radio-button>
              <el-radio-button label="year">年度</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="usageFreqChart" class="chart-container"></div>
      </el-card>
      
      <el-card shadow="hover" class="chart-card">
        <template #header>
          <div class="flex justify-between items-center">
            <span>车辆行驶里程（公里）</span>
            <el-radio-group v-model="mileageType" size="small" @change="loadData">
              <el-radio-button label="month">月度</el-radio-button>
              <el-radio-button label="quarter">季度</el-radio-button>
              <el-radio-button label="year">年度</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="mileageChart" class="chart-container"></div>
      </el-card>
    </div>
    
    <el-card shadow="hover" class="mb-6">
      <template #header>
        <div class="flex justify-between items-center">
          <span>车辆使用时长分布</span>
        </div>
      </template>
      <div ref="usageDurationChart" style="height: 400px; width: 100%"></div>
    </el-card>
    
    <el-card shadow="hover">
      <template #header>
        <div class="flex justify-between items-center">
          <span>车辆使用详情</span>
        </div>
      </template>
      <el-table 
        :data="usageRecords" 
        border 
        stripe 
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="vehicleNo" label="车牌号" width="120" />
        <el-table-column prop="startDate" label="开始日期" width="120" />
        <el-table-column prop="endDate" label="结束日期" width="120" />
        <el-table-column prop="duration" label="使用时长(小时)" width="120" />
        <el-table-column prop="mileage" label="行驶里程(公里)" width="120" />
        <el-table-column prop="driver" label="驾驶员" width="120" />
        <el-table-column prop="department" label="用车部门" width="150" />
        <el-table-column prop="purpose" label="用车事由" min-width="200" />
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import axios from 'axios'

export default {
  name: 'UsageAnalysisView',
  components: {
    Document
  },
  setup() {
    // 图表实例
    let usageFreqChartInstance = null
    let mileageChartInstance = null
    let usageDurationChartInstance = null
    
    // 图表DOM引用
    const usageFreqChart = ref(null)
    const mileageChart = ref(null)
    const usageDurationChart = ref(null)
    
    // 数据状态
    const vehicles = ref([])
    const selectedVehicle = ref(null)
    const dateRange = ref([])
    const usageFreqType = ref('month')
    const mileageType = ref('month')
    const usageRecords = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const loading = ref(false)
    
    // 日期快捷选项
    const dateShortcuts = [
      {
        text: '最近一周',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          return [start, end]
        },
      },
      {
        text: '最近一个月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          return [start, end]
        },
      },
      {
        text: '最近三个月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          return [start, end]
        },
      },
    ]
    
    // 模拟数据
    const mockData = {
      usageFreq: {
        month: ['1月', '2月', '3月', '4月', '5月', '6月'],
        data: [10, 15, 12, 8, 20, 16]
      },
      mileage: {
        month: ['1月', '2月', '3月', '4月', '5月', '6月'],
        data: [520, 680, 450, 320, 790, 610]
      },
      usageDuration: {
        categories: ['0-2小时', '2-4小时', '4-6小时', '6-8小时', '8小时以上'],
        data: [15, 25, 30, 20, 10]
      },
      usageDetails: [
        {
          vehicleNo: '京A12345',
          startDate: '2023-01-01',
          endDate: '2023-01-01',
          duration: 4,
          mileage: 120,
          driver: '张三',
          department: '行政部',
          purpose: '公务接待'
        },
        {
          vehicleNo: '京A12345',
          startDate: '2023-01-03',
          endDate: '2023-01-03',
          duration: 6,
          mileage: 180,
          driver: '李四',
          department: '销售部',
          purpose: '客户拜访'
        },
        {
          vehicleNo: '京A12345',
          startDate: '2023-01-05',
          endDate: '2023-01-05',
          duration: 2,
          mileage: 60,
          driver: '王五',
          department: '技术部',
          purpose: '设备维护'
        }
      ]
    }
    
    // 初始化
    onMounted(() => {
      // 初始化日期范围为近一个月
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      dateRange.value = [formatDate(start), formatDate(end)]
      
      // 加载数据
      loadVehicles()
      loadData()
    })
    
    // 加载车辆列表
    const loadVehicles = async () => {
      try {
        // 实际项目中应从API获取
        /*
        const response = await axios.get('/api/vehicles')
        vehicles.value = response
        */
        
        // 模拟数据
        vehicles.value = [
          { id: 1, vehicleNo: '京A12345' },
          { id: 2, vehicleNo: '京B67890' },
          { id: 3, vehicleNo: '京C54321' }
        ]
      } catch (error) {
        ElMessage.error('获取车辆列表失败')
        console.error('获取车辆列表失败:', error)
      }
    }
    
    // 加载数据
    const loadData = async () => {
      loading.value = true
      try {
        // 实际项目中应从API获取数据
        /*
        const params = {
          startDate: dateRange.value[0],
          endDate: dateRange.value[1],
          vehicleId: selectedVehicle.value,
          freqType: usageFreqType.value,
          mileageType: mileageType.value,
          page: currentPage.value,
          size: pageSize.value
        }
        const response = await axios.get('/api/reports/usage-analysis', { params })
        // 使用API返回的数据更新图表
        */
        
        // 模拟数据延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 使用模拟数据更新
        usageRecords.value = mockData.usageDetails
        total.value = mockData.usageDetails.length
        
        // 渲染图表
        nextTick(() => {
          initUsageFreqChart()
          initMileageChart()
          initUsageDurationChart()
        })
      } catch (error) {
        ElMessage.error('加载数据失败')
        console.error('加载数据失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 初始化使用频率图表
    const initUsageFreqChart = () => {
      if (usageFreqChartInstance) {
        usageFreqChartInstance.dispose()
      }
      
      usageFreqChartInstance = echarts.init(usageFreqChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: mockData.usageFreq.month
        },
        yAxis: {
          type: 'value',
          name: '使用天数'
        },
        series: [
          {
            name: '使用天数',
            type: 'bar',
            barWidth: '60%',
            data: mockData.usageFreq.data,
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      }
      
      usageFreqChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        usageFreqChartInstance.resize()
      })
    }
    
    // 初始化里程图表
    const initMileageChart = () => {
      if (mileageChartInstance) {
        mileageChartInstance.dispose()
      }
      
      mileageChartInstance = echarts.init(mileageChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: mockData.mileage.month
        },
        yAxis: {
          type: 'value',
          name: '里程(公里)'
        },
        series: [
          {
            name: '行驶里程',
            type: 'line',
            data: mockData.mileage.data,
            itemStyle: {
              color: '#67C23A'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(103, 194, 58, 0.5)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(103, 194, 58, 0.1)'
                  }
                ]
              }
            }
          }
        ]
      }
      
      mileageChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        mileageChartInstance.resize()
      })
    }
    
    // 初始化使用时长分布图表
    const initUsageDurationChart = () => {
      if (usageDurationChartInstance) {
        usageDurationChartInstance.dispose()
      }
      
      usageDurationChartInstance = echarts.init(usageDurationChart.value)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 0,
          data: mockData.usageDuration.categories
        },
        series: [
          {
            name: '使用时长分布',
            type: 'pie',
            radius: ['30%', '60%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: mockData.usageDuration.categories.map((category, index) => ({
              value: mockData.usageDuration.data[index],
              name: category
            }))
          }
        ]
      }
      
      usageDurationChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        usageDurationChartInstance.resize()
      })
    }
    
    // 导出Excel
    const exportToExcel = () => {
      ElMessage.success('报表导出成功')
      // 实际项目中应调用导出API
      // window.location.href = '/api/reports/usage-analysis/export?startDate=' + dateRange.value[0] + '&endDate=' + dateRange.value[1]
    }
    
    // 处理日期变化
    const handleDateChange = () => {
      loadData()
    }
    
    // 处理页面大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadData()
    }
    
    // 处理页码变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadData()
    }
    
    // 日期格式化
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    return {
      vehicles,
      selectedVehicle,
      dateRange,
      dateShortcuts,
      usageFreqType,
      mileageType,
      usageRecords,
      currentPage,
      pageSize,
      total,
      loading,
      usageFreqChart,
      mileageChart,
      usageDurationChart,
      loadData,
      handleDateChange,
      handleSizeChange,
      handleCurrentChange,
      exportToExcel
    }
  }
}
</script> 